<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElImage, ElTag } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getTableListApi,
  saveTableApi,
  delTableListApi,
  initAppName,
  updateTableApi,
  getOcrApi,
  putTableApi,
  delTableApi
} from '@/api/data'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive, onMounted, h } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
// import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { Car } from './types'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const ids = ref<string[]>([])
import { ElNotification, ElResult } from 'element-plus'
import { useRouter } from 'vue-router'
const { push } = useRouter()
onMounted(() => {
  if (userStore.getUserInfo?.cid == -1) {
    ElNotification({
      title: '注意',
      type: 'warning',
      // Should pass a function if VNode contains dynamic props
      message: () =>
        h(ElResult, {
          subTitle: '请先填写企业基本信息!',
          'onUpdate:modelValue': (val: string | number) => {
            checked.value = val
          }
        })
    })
    push({ path: '/basic' })
  }
})

initAppName('Cars')
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      motorcadeId: userStore.getUserInfo?.cid,
      ...unref(searchParams)
    })
    console.log(res.data.data.rows)
    return {
      list: res.data.data.rows,
      total: res.data.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delTableApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const uploadData = ref(new FormData())
const uploadSectionFile = (param) => {
  console.log(param)
  //自定义文件上传
  const fileObj = param.file
  const fileName =
    param.data.sort + '_' + fileObj.name.split('.')[0] + '.' + fileObj.name.split('.')[1]
  uploadData.value.append('files', fileObj, fileName)
  console.log(uploadData.value.getAll('files'))
  uploadOcrData()
}

const { t } = useI18n()
const uploadSun = ref<UploadInstance>()
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
  // 创建一个新的 FormData 对象来存储筛选后的文件
  const newFormData = new FormData()

  // 遍历原始 FormData 对象中的所有文件
  for (const [key, value] of uploadData.value.entries()) {
    const na = value.name.split('_')[1]
    if (key === 'files' && na !== file.name.split('_')[0]) {
      // 如果文件名称不符合移除条件，则添加到新的 FormData 对象中
      newFormData.append(key, value)
    }
  }
  uploadData.value = newFormData
  console.log(uploadData.value.getAll('files'))
  // const it = uploadData.value.getAll('files').filter((item) => {
  //   return item.name !== file.name
  // })
}
// const handleExceed: UploadProps['onExceed'] = (files) => {
//   console.log(files)
//   console.log(uploadSun.value)
//   uploadSun.value!.clearFiles()
//   const file = files[0] as UploadRawFile
//   file.uid = genFileId()
//   uploadSun.value!.handleStart(file)
// }

const fileList1 = ref<[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])

const fileList2 = ref<[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])

const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'motorcadeId',
  //   search: {
  //     hidden: true
  //   },
  //   value: 1,
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     hidden: true
  //   },
  //   table: {
  //     hidden: true
  //   }
  // },
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: '编号',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'carName',
    label: '车辆名称',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'carLevel',
    label: '车型',
    slots: {
      default: (data) => {
        return (
          <ElTag type="primary">
            {data.row.carLevel == 1
              ? '5座B级油车'
              : data.row.carLevel == 2
                ? '7座GL8'
                : data.row.carLevel == 12
                  ? '5座新能源B级车'
                  : data.row.carLevel == 13
                    ? '7座新能源商务车'
                    : data.row.carLevel == 5
                      ? '考斯特'
                      : data.row.carLevel == 6
                        ? '33座中巴'
                        : data.row.carLevel == 7
                          ? '45座大巴'
                          : data.row.carLevel == 8
                            ? '50座大巴'
                            : ''}
          </ElTag>
        )
      }
    },
    search: {
      component: 'Input'
    },
    form: {
      component: 'Select',
      componentProps: {
        style: {
          width: '100%'
        },
        options: [
          {
            label: '5座B级油车',
            value: 1
          },
          {
            label: '5座新能源B级车',
            value: 12
          },
          {
            label: '7座GL8',
            value: 2
          },
          {
            label: '7座新能源商务车',
            value: 13
          },
          {
            label: '考斯特',
            value: 5
          },
          {
            label: '33座中巴',
            value: 6
          },
          {
            label: '45座大巴',
            value: 7
          },
          {
            label: '50座大巴',
            value: 8
          }
        ]
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'driverLicense',
    label: '行驶证',
    search: {
      hidden: true
    },
    slots: {
      default: (data) => {
        return (
          <img
            style="max-width: 90%; height: auto;"
            src={
              data.row.driverLicense
                ? data.row.driverLicense.split(',')[data.row.driverLicense.split(',').length - 1]
                : ''
            }
          />
        )
      }
    },
    form: {
      component: 'Upload',
      componentProps: {
        data: { sort: 'driverLicense' },
        action: 'string',
        ref: 'uploadSun',
        fileList: fileList1,
        onRemove: handleRemove,
        limit: 1,
        // onExceed: handleExceed,
        // autoUpload: false,
        httpRequest: uploadSectionFile
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          return (
            <img
              style="max-width: 90%; height: auto;"
              src={data.driverLicense.split(',')[data.driverLicense.split(',').length - 1]}
            />
          )
        }
      }
    }
  },
  {
    field: 'insurance',
    label: '保险',
    search: {
      hidden: true
    },
    slots: {
      default: (data) => {
        return (
          <img
            style="max-width: 90%; height: auto;"
            src={
              data.row.insurance
                ? data.row.insurance.split(',')[data.row.insurance.split(',').length - 1]
                : ''
            }
          />
        )
      }
    },
    form: {
      component: 'Upload',
      componentProps: {
        data: { sort: 'insurance' },
        action: 'string',
        ref: 'uploadSun',
        fileList: fileList2,
        onRemove: handleRemove,
        limit: 1,
        // onExceed: handleExceed,
        // autoUpload: false,
        httpRequest: uploadSectionFile
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          return (
            <ElImage
              style="max-width: 90%; height: auto;"
              src={data.insurance.split(',')[data.insurance.split(',').length - 1]}
            />
          )
        }
      }
    }
  },
  {
    field: 'carNumber',
    label: '车牌',
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'carType',
    label: '机动车类型',
    search: {
      hidden: true
    }
  },
  // {
  //   field: 'importance',
  //   label: '车辆保险',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       style: {
  //         width: '100%'
  //       },
  //       options: [
  //         {
  //           label: '重要',
  //           value: 3
  //         },
  //         {
  //           label: '良好',
  //           value: 2
  //         },
  //         {
  //           label: '一般',
  //           value: 1
  //         }
  //       ]
  //     }
  //   },
  //   detail: {
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <ElTag
  //             type={
  //               data.importance === 1 ? 'success' : data.importance === 2 ? 'warning' : 'danger'
  //             }
  //           >
  //             {data.importance === 1
  //               ? t('tableDemo.important')
  //               : data.importance === 2
  //                 ? t('tableDemo.good')
  //                 : t('tableDemo.commonly')}
  //           </ElTag>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'property',
    label: '使用性质',
    search: {
      hidden: true
    }
  },
  {
    field: 'regDate',
    label: '注册日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'engineNumber',
    label: '发动机号',
    search: {
      hidden: true
    }
  },
  {
    field: 'issueDate',
    label: '发证日期',
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  {
    field: 'content',
    label: t('exampleDemo.content'),
    search: {
      hidden: true
    },
    table: {
      show: false
    },
    form: {
      component: 'Editor',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          return <div innerHTML={data.content}></div>
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton
                v-show={!data.row.pass}
                type="primary"
                onClick={() => action(data.row, 'edit')}
              >
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" onClick={() => action(data.row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton v-show={!data.row.pass} type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
  fileList1.value.length = 0
  fileList2.value.length = 0
}
const closeDialog = () => {
  uploadData.value = new FormData()
}
const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  // await delTableApi(row.id)
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  console.log(row)
  fileList1.value.length = 0
  fileList2.value.length = 0
  driverLicense.value.length = 0
  insurance.value.length = 0
  if (row.driverLicense && row.driverLicense != '') {
    row.driverLicense.split(',').forEach((item) => {
      fileList1.value.push({ url: item })
    })
  }
  if (row.insurance && row.insurance != '') {
    row.insurance.split(',').forEach((item) => {
      fileList2.value.push({ url: item })
    })
  }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)
const driverLicense = ref([])
const insurance = ref([])

const uploadOcrData = async () => {
  const write = unref(writeRef)
  const uploadRes = await updateTableApi(uploadData.value)
  console.log(uploadRes.data.data)
  const imgArr = uploadRes.data.data
  driverLicense.value.length = 0
  insurance.value.length = 0
  imgArr.forEach((item: any) => {
    const type = item.split('/')[item.split('/').length - 1].split('_')[0]
    if (type === 'driverLicense') {
      driverLicense.value.push(item)
    } else if (type === 'insurance') {
      insurance.value.push(item)
    }
  })
  for (const item of driverLicense.value) {
    try {
      const ocrRes = await getOcrApi({ url: item, type: 'Vehicle' })
      console.log(JSON.parse(ocrRes.data.body.data))
      const jsonData = JSON.parse(ocrRes.data.body.data)
      const face = jsonData.data.face ? jsonData.data.face.data : null
      const back = jsonData.data.back ? jsonData.data.back.data : null
      const values: Car = {}
      if (face) {
        face.licensePlateNumber ? (values.carNumber = face.licensePlateNumber) : null
        face.engineNumber ? (values.engineNumber = face.engineNumber) : null
        face.owner ? (values.owner = face.owner) : null
        face.registrationDate ? (values.regDate = face.registrationDate) : null
        face.useNature ? (values.property = face.useNature) : null
        face.vehicleType ? (values.carType = face.vehicleType) : null
        face.model ? (values.carName = face.model) : null
        face.issueDate ? (values.issueDate = face.issueDate) : null
      } else if (back) {
        back.licensePlateNumber ? (values.carNumber = back.licensePlateNumber) : null
        // back.passengerCapacity ? (values.carNumber = back.passengerCapacity) : null
      }
      await write?.setValues(values)
    } catch (e) {
      console.log(e)
    }
  }
}

const save = async () => {
  const write = unref(writeRef)
  console.log('refWrite', uploadData.value.getAll('files'))

  const formData = await write?.submit()
  console.log(formData)
  const f1 = []
  const f2 = []
  fileList1.value.forEach((item) => {
    f1.push(item.url)
  })
  fileList2.value.forEach((item) => {
    f2.push(item.url)
  })
  const arr1 = [...f1, ...driverLicense.value]
  const arr2 = [...f2, ...insurance.value]
  formData.driverLicense = arr1[arr1.length - 1]
  formData.insurance = arr2[arr2.length - 1]
  if (formData) {
    let api = saveTableApi
    if (actionType.value === 'edit') {
      api = putTableApi
    }
    formData.motorcadeId = userStore.getUserInfo?.cid
    saveLoading.value = true
    const res = await api(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
        uploadData.value = new FormData()
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('exampleDemo.del') }}
      </BaseButton> -->
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :image-preview="['driverLicense', 'insurance']"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" @close="closeDialog">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
<style>
.el-upload__input {
  display: block;
}
</style>
